package test.y2020;

import cn.hutool.core.lang.Console;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author song
 * @date 2020/4/9 16:23
 */
public class April5 {

    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();
    private static final ReentrantLock RE_ENTRANT_LOCK = new ReentrantLock();
    private static final Executor EXECUTOR = new ThreadPoolExecutor(10, 100, 100, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100), (ThreadFactory) Thread::new);

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            EXECUTOR.execute(April5::intNum);
        }
    }

    private static void intNum() {
        boolean tryLock = RE_ENTRANT_LOCK.tryLock();
        System.out.println("尝试是否能够拿到锁: " + tryLock);
        RE_ENTRANT_LOCK.lock();
        try {
            Thread thread = Thread.currentThread();
            Console.error(ATOMIC_INTEGER.getAndIncrement());
            Console.error(String.format("线程：【%s】 id：【%s】 获取锁是否成功？ %s ；是否公平？ %s", thread.getName(), thread.getId(), RE_ENTRANT_LOCK.isLocked(), RE_ENTRANT_LOCK.isFair()));

            thread.interrupt();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            RE_ENTRANT_LOCK.unlock();
        }
    }
}
